package com.ruoyi.web.websocket;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.messageDispose.CustomerMessageDispose;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wwy
 * @date 2021-02-28 9:16
 */
@ServerEndpoint(value = "/api/messageSocket")
@Component
public class CustomerMessageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerMessageService.class);
    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();
    /**
     * 在线用户
     */
    public static Map<String,Session> userClients = new ConcurrentHashMap<>();

    private CustomerMessageDispose customerMessageDispose = new CustomerMessageDispose();


    @OnOpen
    public void onOpen(Session session) {
        LOGGER.info("有新的客户端连接了: {}", session.getId());
        //将新用户存入在线的组
        clients.put(session.getId(), session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        LOGGER.info("有用户断开了, id为:{}", session.getId());
        //将掉线的用户移除在线的组里
        clients.remove(session.getId());
        String userId = "";
        for (Map.Entry<String, Session> stringSessionEntry : userClients.entrySet()) {
            Session sessionValue = stringSessionEntry.getValue();
            String userIdKey = stringSessionEntry.getKey();
            if(session == sessionValue){
                userId = userIdKey;
                break;
            }
        }
        userClients.remove(userId);
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message,Session session) {
        LOGGER.info("服务端收到客户端发来的消息: {}", message);
        Message message1 = JSONObject.parseObject(message, Message.class);
        String userId = message1.getUserId();
        userClients.put(userId,session);
        //消息处理
        customerMessageDispose.messageDispose(message1);
    }

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }
    /**
     * 根据用户id发送消息
     * @param userId
     * @param message
     */
    public void sendMessage(String userId,String message){
        Session session = userClients.get(userId);
        session.getAsyncRemote().sendText(message);
    }
}
